<?php

namespace App\Models\Divination;

use App\Models\BasicModel;
use App\Models\Mental\Logs;
use App\Models\User;
use App\Models\Users\MoneyLog;
use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\Models\SiteApp
 *
 * @property int $id ID
 * @property int|null $status 状态 0 未支付 1已支付 2 无人回答 3 有人回答 4 回答完毕
 **/
class Divination extends BasicModel
{
	use HasDateTimeFormatter;
    use SoftDeletes;

    protected $table = 'divination';


    public function answers()
    {
        return $this->hasMany(Answer::class, 'div_id');
    }

    public function pay($uid, $oid): void
    {
        $order=self::find($oid);
        if($order->status==0){
            $user=User::query()->find($uid);
            if($user->money<$order->price){
                throw new \Exception('余额不足');
            }
            (new MoneyLog())->add($uid,-$order->price,'占卜提问',2,$oid);
            $order->status=1;
            $order->pay_time=Carbon::now()->toDateTimeString();
            $order->save();
        }
    }


    public function user()
    {
        return $this->belongsTo(User::class, 'uid', 'id');
    }

    public static function boot(): void
    {
        parent::boot();
        static::deleting(function($div) {
            $div->answers()->delete();
        });
    }
}
